#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1

int main(void) {
    char write_msg[BUFFER_SIZE] = "GreetIngs";
    char read_msg[BUFFER_SIZE];
    
    int fd[2], fd2[2];
    pid_t pid;

    if( pipe(fd) == -1 ) {
        fprintf(stderr, "Pipe failed");
        return 1;
    }
    if( pipe(fd2) == -1 ) {
        fprintf(stderr, "Pipe failed");
        return 1;
    }

    pid = fork();
    
    if(pid < 0) {
        fprintf(stderr, "Fork failed");
        return 1;
    }

    if(pid > 0) {
        close(fd[READ_END]);
        write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
        close(fd[WRITE_END]);

        close(fd2[WRITE_END]);
        read(fd2[READ_END], read_msg, BUFFER_SIZE);
        printf("read2 %s\n", read_msg);
        close(fd2[READ_END]);
    }
    else {
        close(fd[WRITE_END]);
        read(fd[READ_END], read_msg, BUFFER_SIZE);
        printf("read1 %s\n", read_msg);
        close(fd[READ_END]);

        memcpy(write_msg,read_msg,sizeof(read_msg));
        int len = strlen(write_msg);
        for(int i = 0; i < len; ++ i) {
            if('A' <= write_msg[i] && write_msg[i] <= 'Z') {
                write_msg[i] -= 'A';
                write_msg[i] += 'a';
            }
            else {
                write_msg[i] -= 'a';
                write_msg[i] += 'A';
            }
        }
        close(fd2[READ_END]);
        write(fd2[WRITE_END], write_msg, strlen(write_msg)+1);
        close(fd2[WRITE_END]);
    }
    return 0;
}
